package com.oss.base.util;

import java.io.IOException;

import org.apache.struts2.ServletActionContext;
import org.oss.client.dto.BaseResponse;
import org.oss.util.JsonMapper;

import com.aliyuncs.exceptions.ClientException;
import com.oss.base.BaseConst;

public class HttpUtil {

	public static <T extends BaseResponse> T buildFailedRes(Class<T> clazz,Exception e){
		
		try {
			T t = clazz.newInstance();
			t.setResultCode(BaseConst.RESPONSE_CODE_FAILED);
			t.setResultMsg(e.getMessage());
			return t;
		} catch (InstantiationException e1) {
			e1.printStackTrace();
			return null;
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
			return null;
		}
	}
	
	
	public static <T extends BaseResponse> T buildFailedRes(Class<T> clazz,ClientException e){
		
		try {
			T t = clazz.newInstance();
			t.setResultCode(BaseConst.RESPONSE_CODE_FAILED);
			t.setResultMsg(e.getErrCode()+":"+e.getErrMsg());
			return t;
		} catch (InstantiationException e1) {
			e1.printStackTrace();
			return null;
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
			return null;
		}
	}
	
	public static void writeRes(Object obj){
		try {
			ServletActionContext.getResponse().setContentType("text/json;charset=UTF-8");
			ServletActionContext.getResponse().getWriter().write(JsonMapper.buildNonDefaultMapper().toJson(obj));
			ServletActionContext.getResponse().getWriter().flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}
